<html>
<head><title>Calculator</title></head>
<body>

<h1>Calculator</h1>
(Ver 1.0 04/02/2012 by Eric Sun)<br />
Type an expression in the following box (e.g., 10.5+20*3/25).
<p>
<form method="GET">
<input type="text" name="expr"><input type="submit" value="Calculate">
</form>
</p>
</body>
</html>

<?php
	function isvalid($expr)
	{
		//divide by zero
		if(preg_match("/\/0/", $expr) > 0)
			exit("<h2>Result</h2>$expr =");
			
		//letters
		if(preg_match("/[a-z]/", $expr) > 0)
			exit("<h2>Result</h2>Invalid input expression $expr.");
		
		//double minus
		if(preg_match("/--/", $expr) > 0)
			exit("<h2>Result</h2>Invalid input expression $expr.");
			
	
		$oprnd = "(-[0-9]|[0-9])";
		$regex = "/" . $oprnd . "\*" . $oprnd . "/";
		$matches += preg_match($regex, $expr);
		$regex = "/" . $oprnd . "\/" . $oprnd . "/";
		$matches += preg_match($regex, $expr);
		$regex = "/" . $oprnd . "\+" . $oprnd . "/";
		$matches += preg_match($regex, $expr);
		$regex = "/-[0-9]/";
		$matches += preg_match($regex, $expr);
		
		if($matches == 0)
			return false;
		
		return true;
	}
	
	$expr = $_GET['expr'];	
	
	if($expr == NULL)
		exit();
	
	if(!isvalid($expr))
		exit("<h2>Result</h2>Invalid input expression $expr.");
	
	$val = eval("return($expr);");
	
	echo("<h2>Result</h2>$expr = $val");

?>